package net.lab1024.sa.admin.module.business.order.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.lab1024.sa.admin.module.business.order.dao.OrderDao;
import net.lab1024.sa.admin.module.business.order.domain.entity.OrderEntity;
import net.lab1024.sa.admin.module.business.order.domain.form.OrderAddForm;
import net.lab1024.sa.admin.module.business.order.domain.form.OrderQueryForm;
import net.lab1024.sa.admin.module.business.order.domain.form.OrderUpdateForm;
import net.lab1024.sa.admin.module.business.order.domain.vo.OrderNum;
import net.lab1024.sa.admin.module.business.order.domain.vo.OrderNumVO;
import net.lab1024.sa.admin.module.business.order.domain.vo.OrderVO;
import net.lab1024.sa.admin.module.business.place.manager.PlaceCacheManager;
import net.lab1024.sa.admin.module.system.type.Dao.TypeDao;
import net.lab1024.sa.admin.module.system.type.domain.TypeEntity;
import net.lab1024.sa.admin.module.system.type.service.TypeService;
import net.lab1024.sa.admin.util.IdGenerator;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.base.module.support.operatelog.domain.OperateLogVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 订单 Service
 *
 * @Author syf
 * @Date 2025-05-16 10:02:50
 * @Copyright 畅想科技
 */

@Service
public class OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private TypeDao typeDao;
    @Resource
    private PlaceCacheManager placeCacheManager;

    /**
     * 分页查询
     *
     * @param queryForm
     * @return
     */
    public PageResult<OrderVO> queryPageOrderByTime(OrderQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        OrderQueryForm queryForm1 = queryForm;
        if (queryForm.getOrderKind() == null || queryForm.getOrderKind() == 0) {
            queryForm.setOrderKind(null);
        }
        List<OrderVO> list = orderDao.queryPageOrderByTime(page, queryForm);
        List<TypeEntity> typeList = typeDao.selectByKey("order_type");
        List<String> orderStateNames = typeList.stream()
                .map(TypeEntity::getTypeName)
                .collect(Collectors.toList());

        // 遍历订单并设置状态名称
        for (OrderVO orderVO : list) {
            orderVO.setOrderStateName(orderStateNames.get(Math.toIntExact(orderVO.getOrderState()) - 1));
            orderVO.setOrderStartName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderStart()));
            orderVO.setOrderEndName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderEnd()));
        }
        PageResult<OrderVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }
    public PageResult<OrderVO> queryPage(OrderQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        OrderQueryForm queryForm1 = queryForm;
        if (queryForm.getOrderKind() == null || queryForm.getOrderKind() == 0) {
            queryForm.setOrderKind(null);
        }
        List<OrderVO> list = orderDao.queryPage(page, queryForm);
        List<TypeEntity> typeList = typeDao.selectByKey("order_type");
        List<String> orderStateNames = typeList.stream()
                .map(TypeEntity::getTypeName)
                .collect(Collectors.toList());

        // 遍历订单并设置状态名称
        for (OrderVO orderVO : list) {
            orderVO.setOrderStateName(orderStateNames.get(Math.toIntExact(orderVO.getOrderState()) - 1));
            orderVO.setOrderStartName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderStart()));
            orderVO.setOrderEndName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderEnd()));
        }
        PageResult<OrderVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }
    //    private String determineOrderStateName(OrderVO order, List<String> stateNames) {
//        if (order.getOrderOpen() == null) {
//            return stateNames.get(0);
//        } else if (order.getJdyId() == null) {
//            return stateNames.get(1);
//        } else if (order.getCompeteTime() == null) {
//            return stateNames.get(2);
//        } else {
//            return stateNames.get(3);
//        }
//    }
    public ResponseDTO<OrderVO> detail(String id) {
        OrderVO orderVO = orderDao.detail(id);
        List<TypeEntity> typeList = typeDao.selectByKey("order_type");
        List<TypeEntity> stateList = typeDao.selectByKey("order_content");
        if (orderVO == null) {
            return ResponseDTO.okMsg("订单不存在");
        }
        if(orderVO.getOrderKind() == 1||orderVO.getOrderKind() ==3 ) {
            String content = orderVO.getOrderContent();
            String num = orderVO.getOrderNum();
            int digit = 1;
            List<String> contentResult = new ArrayList<>();
            List<String> numResult = new ArrayList<>();
            for (int i = 0; i < num.length(); i += digit) {
                int end = Math.min(i + digit, num.length());
                numResult.add(num.substring(i, end));
            }
            for (int i = 0; i < content.length(); i += digit) {
                int end = Math.min(i + digit, content.length());
                contentResult.add(content.substring(i, end));
            }
            String contentName = "";
            for (int i = 0; i < contentResult.size(); i++) {

                for (TypeEntity state : stateList) {
                    if (Objects.equals(state.getTypeId(), Long.valueOf(contentResult.get(i)))) {
                        if (contentName.isEmpty()) {
                            contentName = state.getTypeName() + " " + numResult.get(i) + "件";
                        } else {
                            contentName += "," + state.getTypeName() + " " + numResult.get(i) + "件";
                        }
                    }
                }

            }
            orderVO.setOrderContentName(contentName);
        }
        if(orderVO.getOrderKind() == 2 ){
            String content = orderVO.getOrderNum();
            orderVO.setOrderContentName(content);
        }
        List<String> orderStateNames = typeList.stream()
                .map(TypeEntity::getTypeName)
                .collect(Collectors.toList());
        orderVO.setOrderStateName(orderStateNames.get(Math.toIntExact(orderVO.getOrderState()) - 1));
        orderVO.setOrderStartName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderStart()));
        orderVO.setOrderEndName(placeCacheManager.queryPlaceTreeByName(orderVO.getOrderEnd()));
        return ResponseDTO.ok(orderVO);
    }

    public ResponseDTO<List<OrderVO>> queryOrderByJdyId(String jdyId) {
        List<OrderVO> orderVO = orderDao.queryOrderByJdyId(jdyId);
        return ResponseDTO.ok(orderVO);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(OrderAddForm addForm) {
        OrderEntity orderEntity = SmartBeanUtil.copy(addForm, OrderEntity.class);
//      orderEntity.setOrderContent(addForm.getOrderContent());
//        if (orderEntity.getOrderOpen()==null){
//            orderEntity.setOrderState(0L);
//
//        }else if (orderEntity.getJdyId()==null){
//            orderEntity.setOrderState(1L);
//        }else if (orderEntity.getCompeteTime()==null){
//            orderEntity.setOrderState(4L);
//
//        }else{
//            orderEntity.setOrderState(5L);
//        }
        Long id = IdGenerator.generateId();
        orderEntity.setOrderId(String.valueOf(id));
        orderEntity.setCreateTime(LocalDateTime.now());
        orderDao.insert(orderEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     * @param updateForm
     * @return
     */
    public ResponseDTO<String> update(OrderUpdateForm updateForm) {
        OrderEntity orderEntity = SmartBeanUtil.copy(updateForm, OrderEntity.class);
        orderEntity.setJdyTime(LocalDateTime.now());
        orderDao.updatebyId(orderEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    public ResponseDTO<String> batchDelete(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        orderDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    public ResponseDTO<List<OrderNum>> setOrderNum() {
        List<OrderNumVO> orderNums =orderDao.selectOrderNums();
        List<OrderNum> orderNumList = new ArrayList<>();
        OrderNum orderNum1 = new OrderNum();
        OrderNum orderNum2 = new OrderNum();
        OrderNum orderNum3 = new OrderNum();
        OrderNum orderNum4 = new OrderNum();
        List<String> nums1 = new ArrayList<>();
        List<String> nums2 = new ArrayList<>();
        List<String> nums3 = new ArrayList<>();
        List<String> nums4 = new ArrayList<>();
        for (OrderNumVO orderNum : orderNums) {
            if (Objects.equals(orderNum.getOrderKind(), "1")) {
                        nums1.add(orderNum.getDailyOrders());
            }else if (Objects.equals(orderNum.getOrderKind(), "2")) {
                nums2.add(orderNum.getDailyOrders());
            }else if (Objects.equals(orderNum.getOrderKind(), "3")) {
                nums3.add(orderNum.getDailyOrders());
            }else if (Objects.equals(orderNum.getOrderKind(), "4")) {
                nums4.add(orderNum.getDailyOrders());
            }
        }
        orderNum1.setId(1L);
        orderNum1.setName("代取快递");
        orderNum1.setData(nums1);
        orderNum2.setId(2L);
        orderNum2.setName("代买物品");
        orderNum2.setData(nums2);
        orderNum3.setId(3L);
        orderNum3.setName("代取快递");
        orderNum3.setData(nums3);
        orderNum4.setId(4L);
        orderNum4.setName("代办事");
        orderNum4.setData(nums4);
        orderNumList.add(orderNum1);
        orderNumList.add(orderNum2);
        orderNumList.add(orderNum3);
        orderNumList.add(orderNum4);
        return ResponseDTO.ok(orderNumList);
    }
    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Integer orderId) {
        if (null == orderId) {
            return ResponseDTO.ok();
        }

        orderDao.deleteById(orderId);
        return ResponseDTO.ok();
    }
}
